package com.afishing.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    private FilterConfig config;
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    public void destroy() {
        this.config = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        if (uri.contains(".css") || uri.contains("login-servlet") ||uri.contains("index.jsp")||uri.contains("register-servlet")||uri.contains("register.jsp")) {
            chain.doFilter(request, response);
        }else{
            //获取session
            HttpSession session = req.getSession();
            if (session.getAttribute("user") == null) {
                //未登录
                System.out.println("目前未登录");
                req.setAttribute("login_msg", "您尚未登录，请登录");
                req.getRequestDispatcher("/index.jsp").forward(request, response);
            } else {
                System.out.println("目前已登录");
                //已登录
                chain.doFilter(request, response);
            }
        }

    }
}
